<?php

class AddNews extends MY_Controller {

    var $path;
    
    public function __construct() {
        parent::__construct();
        
        if($this->session->userdata('user_type') != 1 || $this->session->userdata('user_type') == null){
            show_error("You have no permission here");
        }
    }

    function initForm() {
        
        $this->data['main_title'] = "Add News";
        $this->data['action'] = '';
        $news = array(
            'id' => '',
            'news_name' => '',
            'news_path' => ''
        );
        $this->data['news'] = $news;

        $newsName = array(
            'id' => 'newsName',
            'name' => 'newsName'
        );

        $newsPath = array(
            'id' => 'newsSelect',
            'name' => 'newsSelect'
        );

        $this->data['newsName'] = $newsName;
        $this->data['newsPath'] = $newsPath;
    }

    function index() {
        $this->initForm();
        $this->data['main_content'] = 'add_news';
        $this->load->view('includes/template', $this->data);
    }

    function uploadFile() {

        $newsName = $this->input->post('newsName');
        
        $this->initForm();
        $config["upload_path"] = "upload/news/";
        $config["allowed_types"] = "jpg|gif|png|jpeg";
        $config["max_size"] = 2048;
//        $config["max_height"] = 1024;
//        $config["max_width"] = 1024;
        $this->load->library("upload", $config);
        if ($this->upload->do_upload("upload")) {
            $data = $this->upload->data();
            rename($data['full_path'], $data['file_path'] . $newsName . $data['file_ext']);
            $news = array(
                'NEWS_NAME' => $this->input->post('newsName'),
                'NEWS_PATH' => "upload/news/" . $newsName . $data['file_ext']
            );
            $this->load->model('News_Model');
            $this->News_Model->insertNews($news);
            echo "<script>
                    alert('News has been saved successfull!!!');
                    window.location.href='AddNews';
                  </script>";
        } else {
            echo $this->upload->display_errors();
            echo anchor("AddNews","Back");
        }
    }
}

?>
